import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

def drop_path(x, drop_prob: float = 0., training: bool = False):
    if drop_prob == 0. or not training:
        return x
    keep_prob = 1 - drop_prob
    shape = (x.shape[0],) + (1,) * (x.ndim - 1)  
    random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
    random_tensor.floor_() 
    output = x.div(keep_prob) * random_tensor
    return output

class DropPath(nn.Module):
    def __init__(self, drop_prob=None):
        super(DropPath, self).__init__()
        self.drop_prob = drop_prob

    def forward(self, x):
        return drop_path(x, self.drop_prob, self.training)

class LayerNormalization(nn.Module):
    def __init__(self, normalized_size, eps=1e-6):
        super(LayerNormalization, self).__init__()
        self.normalized_size = normalized_size
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(normalized_size))
        self.bias = nn.Parameter(torch.zeros(normalized_size))
        
    def forward(self, x):
        u = x.mean(1, keepdim=True) 
        s = (x - u).pow(2).mean(1, keepdim=True)
        x = (x - u) / torch.sqrt(s + self.eps)
        x = self.weight[:, None, None] * x + self.bias[:, None, None]
        return x

class BasicBlock(nn.Module):
    def __init__(self, dim, drop_path_rate=0.0, layer_scale_init_value=1e-6):
        super(BasicBlock, self).__init__()
        
        self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim, bias=True)
        
        self.norm = LayerNormalization(dim)
        
        self.pwconv1 = nn.Linear(dim, 4 * dim) 
        self.act = nn.GELU()
        self.pwconv2 = nn.Linear(4 * dim, dim) 
        
        self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(dim), 
                                requires_grad=True) if layer_scale_init_value > 0 else None
        
        self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
        
    def forward(self, x):
        input = x
        x = self.dwconv(x)  
        x = self.norm(x)
        x = x.permute(0, 2, 3, 1)
        x = self.pwconv1(x)
        x = self.act(x)
        x = self.pwconv2(x)
        
        if self.gamma is not None:
            x = self.gamma * x
            
        x = x.permute(0, 3, 1, 2)

        x = input + self.drop_path(x)
        return x

class Conv_Next(nn.Module):
    def __init__(self, num_classes=100, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], 
                 drop_path_rate=0.15, layer_scale_init_value=1e-6):
        super(Conv_Next, self).__init__()
        
        self.downsample_layers = nn.ModuleList()
        stem = nn.Sequential(
            nn.Conv2d(3, dims[0], kernel_size=4, stride=4, bias=True),
            LayerNormalization(dims[0])
        )
        self.downsample_layers.append(stem)
        
        for i in range(3):
            downsample_layer = nn.Sequential(
                LayerNormalization(dims[i]),
                nn.Conv2d(dims[i], dims[i+1], kernel_size=2, stride=2, bias=True),
            )
            self.downsample_layers.append(downsample_layer)

        self.stages = nn.ModuleList()
        
        dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] 
        cur = 0
        
        for i in range(4):
            stage = nn.Sequential(
                *[BasicBlock(dim=dims[i], 
                           drop_path_rate=dp_rates[cur + j], 
                           layer_scale_init_value=layer_scale_init_value) 
                  for j in range(depths[i])]
            )
            self.stages.append(stage)
            cur += depths[i]

        self.norm = nn.LayerNorm(dims[-1], eps=1e-6) 
        self.head = nn.Linear(dims[-1], num_classes)

        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, (nn.Conv2d, nn.Linear)):
                nn.init.trunc_normal_(m.weight, std=.02)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, LayerNormalization):
                nn.init.constant_(m.weight, 1.0)
                nn.init.constant_(m.bias, 0.0)

    def forward_features(self, x):
        for i in range(4):
            x = self.downsample_layers[i](x)
            x = self.stages[i](x)
        x = x.mean([-2, -1])
        return self.norm(x)

    def forward(self, x):
        x = self.forward_features(x)
        x = self.head(x)
        return x

    def get_classifier(self):
        return self.head

    def reset_classifier(self, num_classes):
        self.head = nn.Linear(self.head.in_features, num_classes) if num_classes > 0 else nn.Identity()

# Model factory functions
def convnext_tiny(num_classes=100, drop_path_rate=0.1):
    return Conv_Next(num_classes=num_classes, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768],
                    drop_path_rate=drop_path_rate)

def convnext_small(num_classes=100, drop_path_rate=0.15):
    return Conv_Next(num_classes=num_classes, depths=[3, 3, 27, 3], dims=[96, 192, 384, 768],
                    drop_path_rate=drop_path_rate)

def convnext_base(num_classes=100, drop_path_rate=0.2):
    return Conv_Next(num_classes=num_classes, depths=[3, 3, 27, 3], dims=[128, 256, 512, 1024],
                    drop_path_rate=drop_path_rate)